package tpo.vista.clientes;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

import tpo.controlador.Sistema;
import tpo.to.ClienteDTO;

public class ModificacionCliente extends JFrame {
	
	private Sistema sistema;
	
	public ModificacionCliente(Sistema sistema){
		super("Modificacion Cliente");
		this.sistema = sistema;
		init();
		setVisible(true);
	}
	
	private void init(){
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		setLayout(new GridBagLayout());
		GridBagConstraints gc = new GridBagConstraints();
		
		List<ClienteDTO> clientesTO = sistema.getClientesDTO();

		JLabel labelCliente = new JLabel ("Cliente");
		JLabel labelDomicilio = new JLabel ("Domicilio");
		JLabel labelTelefono = new JLabel ("Telefono");
		final JComboBox clientesCombo = new JComboBox(clientesTO.toArray());
		final JTextField fieldDomicilio = new JTextField("");
		final JTextField fieldTelefono = new JTextField("");
		JButton button = new JButton("Guardar");
		
		clientesCombo.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JComboBox cb = (JComboBox) e.getSource();
		        ClienteDTO clienteTO = (ClienteDTO) cb.getSelectedItem();
				fieldDomicilio.setText(clienteTO.getDomicilio());
				fieldTelefono.setText(clienteTO.getTelefono());
			}
		});
		
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evento) {
		        ClienteDTO clienteTO = (ClienteDTO) clientesCombo.getSelectedItem();
				sistema.modificarDatosPersonalesCliente(clienteTO.getCodigo(), fieldDomicilio.getText(), fieldTelefono.getText());
				dispose();
				System.out.println("Los datos fueron modificados");
			}
		});
		
		gc.gridx = 0;	// Columna
		gc.gridy = 0;	// Fila
		add(labelCliente, gc);		
		gc.gridx = 1;
		gc.gridy = 0;
		add(clientesCombo, gc);
		
		gc.gridx = 0;
		gc.gridy = 1;
		add(labelDomicilio, gc);		
		gc.gridx = 1;
		gc.gridy = 1;
		fieldDomicilio.setColumns(10);
		add(fieldDomicilio, gc);
		
		gc.gridx = 0;
		gc.gridy = 2;
		add(labelTelefono, gc);		
		gc.gridx = 1;
		gc.gridy = 2;
		fieldTelefono.setColumns(10);
		add(fieldTelefono, gc);
		
		gc.gridx = 0;
		gc.gridy = 9;
		add(button, gc);
		
		if(!clientesTO.isEmpty()) {
			ClienteDTO clienteTO = (ClienteDTO) clientesCombo.getSelectedItem();
			fieldDomicilio.setText(clienteTO.getDomicilio());
			fieldTelefono.setText(clienteTO.getTelefono());
		} else {
			fieldDomicilio.setEnabled(false);
			fieldTelefono.setEnabled(false);
			button.setEnabled(false);
		}

		pack();
		setSize(400, 300);
	}
}

